/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.dict.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.star.framework.dict.entity.Dict;
import cn.star.framework.dict.entity.DictEntry;
import cn.star.framework.dict.repository.DictRepository;
import cn.star.framework.dict.service.DictEntryService;
import cn.star.framework.dict.service.DictService;
import cn.star.framework.service.AbstractService;
import cn.star.framework.type.Status;
import cn.star.framework.util.EnumEntryHelper;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

/**
 * DictServiceImpl<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Service
public class DictServiceImpl extends AbstractService<Dict, String, DictRepository>
    implements DictService {

  @Autowired private DictEntryService dictEntryService;

  public DictServiceImpl(DictRepository repository) {
    super(repository);
  }

  @Override
  public List<DictEntry> getDictEntryValues(String code) {
    Dict dict = this.findOne((root, query, cb) -> cb.equal(root.get("code"), code));
    if (dict != null) {
      return dictEntryService.findAll(
          (root, query, cb) ->
              cb.and(
                  cb.equal(root.get("dictId"), dict.getId()),
                  // 使用的字典一定是启用状态的字典
                  cb.equal(root.get("status"), Status.ENABLED)),
          Sort.by(Order.asc("order")));
    }
    return Collections.emptyList();
  }

  @Override
  public Dict findById(String id) {
    Dict dict = super.findById(id);
    if (dict != null) {
      List<DictEntry> items =
          dictEntryService.findAll(
              (root, query, cb) -> cb.equal(root.get("dictId"), dict.getId()),
              Sort.by(Order.asc("order")));
      dict.setItems(items);
    }

    return dict;
  }

  @Override
  public List<DictEntry> getStaticDictEntryValues(String pk, String code) {
    Set<Class<?>> types = this.getEnumEntryClasses(pk);
    if (CollectionUtil.isNotEmpty(types)) {
      for (Class<?> type : types) {
        if (type.isEnum() && type.getSimpleName().equalsIgnoreCase(code)) {
          return EnumEntryHelper.get(type).getValues().stream()
              .map(
                  e -> {
                    String label = e.getLabel(), value = String.valueOf(e.getValue());
                    DictEntry entry = new DictEntry();
                    entry.setId(value);
                    entry.setDictId(code);
                    entry.setLabel(label);
                    entry.setValue(value);
                    entry.setOrder(1);
                    entry.setStatus(Status.ENABLED);

                    return entry;
                  })
              .collect(Collectors.toList());
        }
      }
    }

    return Collections.emptyList();
  }
}
